package cn.edu.njust.echo;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

@Slf4j
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        Scanner scanner = new Scanner(System.in);
        System.out.print("Input: ");
        String message = scanner.nextLine();

        ctx.writeAndFlush(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8));
        log.info("发送消息{}给服务端", message);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String message = (String) msg;
        log.info("从服务端收到了消息{}", message);

        log.info("关闭连接");
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.error("发生了异常");
        ctx.close();
    }
}
